package com.atguigu.flink.tableapi;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * Created by Smexy on 2023/3/4
 *              streamAPI                      flinksql
 *  编程环境: StreamExectionEnviroment       StreamTableEnvironment
 *
 *  数据模型：DataStream                        Table(动态表)
 *
 */
public class Demo2_Row
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<WaterSensor> ds = env
            .socketTextStream("hadoop103", 8888)
            .map(new WaterSensorMapFunction());


        Table table = tableEnv.fromDataStream(ds);

        table.printSchema();

        Table result = table.select($("id"), $("ts"))
                           .where($("id").isEqual("s1"));

        /*
                把表转换为 DataStream，用之前的API操作

                toDataStream(Table table, Class<T> targetClass): POJO中的属性必须和表中的列一致(名称，数量，类型)
                Row: 代表一行
         */
        DataStream<Row> ds2 = tableEnv.toDataStream(result);

        ds2.map(new MapFunction<Row, String>()
        {
            @Override
            public String map(Row value) throws Exception {
                String id = value.<String>getFieldAs("id");
                Long ts = value.<Long>getFieldAs("ts");
                return id + "," + ts;
            }
        }).print();



        try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }




    }
}
